using System;
using ProtoModels;
using UnityEngine;

public class GGPrizesBackend : BehaviourSingletonInit<GGPrizesBackend>
{
	public delegate void OnCompetitionFinished(LeaderboardsAdapter winnings);

	public delegate void OnPrizesRefreshed();

	public enum DataProvider
	{
		NonSegmented = 0,
		Segmented = 1
	}

	private WinningsDAO winningsModel;

	private static string WinningsFilename = "winningsDao.bytes";

	private bool notificationSent;

	private DateTime cachedCompEnd = new DateTime(0L);

	private int cachedSR = -1;

	private string cachedCountry = string.Empty;

	public WinningsDAO WinningsModel
	{
		get
		{
			return winningsModel;
		}
	}

	private DataProvider dataProvider
	{
		get
		{
			return GGServerConstants.instance.prizeLeaderboardType;
		}
	}

	public event OnCompetitionFinished onCompFinished;

	public event OnPrizesRefreshed onRefreshed;

	public void CheckPrizes(int sR, string country)
	{
		if (winningsModel.winningsLead == null && winningsModel.combWinningsLead == null)
		{
			if (!HasActiveCompTimestamp())
			{
				RefreshWinnings(sR, country);
			}
		}
		else if (!winningsModel.ackReceived)
		{
			SendAckPrize();
		}
	}

	public void ApplyWinnings(LeaderboardsAdapter winnings, WalletManager walletManager)
	{
		for (int i = 0; i < winnings.leaderboards.Count; i++)
		{
			LeaderboardsAdapter.ClientPrize winnings2 = winnings.leaderboards[i].winnings;
			if (winnings2 != null)
			{
				walletManager.AddCurrency(CurrencyType.coins, winnings2.coins);
				walletManager.AddCurrency(CurrencyType.ggdollars, winnings2.cash);
				walletManager.AddCurrency(CurrencyType.diamonds, winnings2.tokens);
			}
		}
		ClearCachedWinningsWinnings();
	}

	private void ClearCachedWinningsWinnings()
	{
		winningsModel.winningsLead = null;
		winningsModel.combWinningsLead = null;
		winningsModel.ackReceived = false;
		Save();
		notificationSent = false;
	}

	public LeaderboardsAdapter GetPrizesIfCompFinished()
	{
		if (isTimestampActive(cachedCompEnd))
		{
			return null;
		}
		if (!winningsModel.ackReceived)
		{
			return null;
		}
		if (winningsModel.winningsLead != null)
		{
			return new LeaderboardsAdapter(winningsModel.winningsLead);
		}
		return new LeaderboardsAdapter(winningsModel.combWinningsLead);
	}

	public TimeSpan TimeToCompEnd()
	{
		if (!HasActiveCompTimestamp())
		{
			return TimeSpan.Zero;
		}
		return cachedCompEnd.Subtract(DateTime.Now);
	}

	private void Update()
	{
		if (HasKnownActiveCompExpired())
		{
			cachedCompEnd = new DateTime(0L);
			CheckPrizes(cachedSR, cachedCountry);
		}
		else if (winningsModel != null && winningsModel.ackReceived && !notificationSent)
		{
			notificationSent = true;
			if (this.onCompFinished != null)
			{
				LeaderboardsAdapter winnings = ((winningsModel.winningsLead == null) ? new LeaderboardsAdapter(winningsModel.combWinningsLead) : new LeaderboardsAdapter(winningsModel.winningsLead));
				this.onCompFinished(winnings);
			}
		}
	}

	public override void Init()
	{
		ReloadModel();
	}

	public void ReloadModel()
	{
		if (!ProtoIO.LoadFromFile<WinningsDAO>(WinningsFilename, out winningsModel))
		{
			winningsModel = new WinningsDAO();
			ProtoIO.SaveToFile(WinningsFilename, winningsModel);
		}
	}

	private void Save()
	{
		ProtoIO.SaveToFileCloudSync(WinningsFilename, winningsModel);
	}

	private void RefreshWinnings(int sR, string country)
	{
		cachedSR = sR;
		cachedCountry = country;
		if (dataProvider == DataProvider.NonSegmented)
		{
			GGServerRequestsBackend.GetPrizesRequest getPrizesRequest = new GGServerRequestsBackend.GetPrizesRequest(sR, country);
			BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetPrizes(getPrizesRequest, SaveWinnings);
		}
		else if (dataProvider == DataProvider.Segmented)
		{
			GGServerRequestsBackend.GetPrizesRequestCombinationLead getPrizesRequest2 = new GGServerRequestsBackend.GetPrizesRequestCombinationLead(sR, country);
			BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetCombinationPrizes(getPrizesRequest2, SaveWinnings);
		}
	}

	private void SendAckPrize()
	{
		GGServerRequestsBackend.AckPrizesRequest ackPrizesRequest = new GGServerRequestsBackend.AckPrizesRequest();
		BehaviourSingletonInit<GGServerRequestsBackend>.instance.AckPrizes(ackPrizesRequest, AckReceived);
	}

	private bool isTimestampActive(DateTime compTime)
	{
		return compTime >= DateTime.Now;
	}

	public void SaveWinnings(GGServerRequestsBackend.ServerRequest request)
	{
		try
		{
			if (this.onRefreshed != null)
			{
				this.onRefreshed();
			}
		}
		catch
		{
		}
		if (request.status != 0)
		{
			return;
		}
		Lead lead = null;
		CombinationLeads combinationLeads = null;
		DateTime dateTime = new DateTime(0L);
		if (dataProvider == DataProvider.NonSegmented)
		{
			lead = request.GetResponse<Lead>();
			dateTime = GGServerRequestsBackend.GetDateTimeCompEnd(lead.compEndTimestamp);
		}
		else
		{
			if (dataProvider != DataProvider.Segmented)
			{
				Debug.Log("exit else");
				return;
			}
			combinationLeads = request.GetResponse<CombinationLeads>();
			dateTime = GGServerRequestsBackend.GetDateTimeCompEnd(combinationLeads.compEndTimestamp);
		}
		if (isTimestampActive(dateTime))
		{
			Debug.Log("exit still active");
			dateTime.AddSeconds(UnityEngine.Random.Range(0, 120));
			cachedCompEnd = dateTime;
		}
		else
		{
			winningsModel.winningsLead = lead;
			winningsModel.combWinningsLead = combinationLeads;
			winningsModel.ackReceived = false;
			Save();
			SendAckPrize();
		}
	}

	public void AckReceived(GGServerRequestsBackend.ServerRequest request)
	{
		if (request.status == GGServerRequestsBackend.ServerRequest.RequestStatus.Success)
		{
			StatusMessage response = request.GetResponse<StatusMessage>();
			if (response.success)
			{
				winningsModel.ackReceived = true;
				Save();
			}
		}
	}

	public bool HasActiveCompTimestamp()
	{
		return cachedCompEnd != new DateTime(0L) && isTimestampActive(cachedCompEnd);
	}

	private bool HasKnownActiveCompExpired()
	{
		return cachedCompEnd != new DateTime(0L) && !isTimestampActive(cachedCompEnd);
	}
}
